<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="800px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="right"
    >
      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="数据源名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入数据源名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据源类型">
                <el-input :value="'Kafka'" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入数据源描述"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>

        <!-- 连接配置 -->
        <el-tab-pane label="连接配置" name="connection">
          <el-form-item label="集群模式" prop="connectionConfig.clusterMode">
            <el-radio-group v-model="formData.connectionConfig.clusterMode" @change="handleClusterModeChange">
              <el-radio :label="false">单节点</el-radio>
              <el-radio :label="true">集群</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 单节点配置 -->
          <template v-if="!formData.connectionConfig.clusterMode">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="服务器地址" prop="connectionConfig.single.host">
                  <el-input v-model="formData.connectionConfig.single.host" placeholder="请输入Kafka服务器地址" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="端口" prop="connectionConfig.single.port">
                  <el-input-number
                    v-model="formData.connectionConfig.single.port"
                    :min="1"
                    :max="65535"
                    controls-position="right"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </template>

          <!-- 集群配置 -->
          <template v-else>
            <el-form-item label="集群地址" prop="connectionConfig.cluster.brokers">
              <el-button
                type="primary"
                size="small"
                @click="addBroker"
                style="margin-bottom: 10px"
              >
                添加Broker
              </el-button>
              <el-table
                :data="formData.connectionConfig.cluster.brokers"
                border
                style="width: 100%"
                empty-text="暂无Broker配置"
              >
                <el-table-column prop="host" label="主机地址" width="300">
                  <template #default="{ row, $index }">
                    <el-input
                      v-model="row.host"
                      placeholder="例如: 192.168.1.100"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="port" label="端口" width="150">
                  <template #default="{ row, $index }">
                    <el-input-number
                      v-model="row.port"
                      :min="1"
                      :max="65535"
                      controls-position="right"
                      style="width: 100%"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template #default="{ $index }">
                    <el-button
                      type="danger"
                      size="small"
                      @click="removeBroker($index)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </template>

          <el-form-item label="客户端ID" prop="connectionConfig.clientId">
            <el-input 
              v-model="formData.connectionConfig.clientId" 
              placeholder="请输入客户端ID"
            />
            <span class="el-form-item__tip">如果不填，系统将自动生成</span>
          </el-form-item>

          <el-form-item label="认证方式" prop="connectionConfig.authType">
            <el-select
              v-model="formData.connectionConfig.authType"
              placeholder="请选择认证方式"
              style="width: 100%"
              @change="handleAuthTypeChange"
            >
              <el-option label="无认证" value="none" />
              <el-option label="SASL/PLAIN" value="sasl_plain" />
              <el-option label="SSL" value="ssl" />
              <el-option label="SASL/SCRAM" value="sasl_scram" />
            </el-select>
          </el-form-item>

          <!-- SASL/PLAIN 认证配置 -->
          <template v-if="formData.connectionConfig.authType === 'sasl_plain'">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名" prop="connectionConfig.saslPlain.username">
                  <el-input v-model="formData.connectionConfig.saslPlain.username" placeholder="请输入用户名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="密码" prop="connectionConfig.saslPlain.password">
                  <el-input
                    v-model="formData.connectionConfig.saslPlain.password"
                    type="password"
                    placeholder="请输入密码"
                    show-password
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </template>

          <!-- SSL 认证配置 -->
          <template v-else-if="formData.connectionConfig.authType === 'ssl'">
            <el-form-item label="CA证书" prop="connectionConfig.ssl.ca">
              <el-input
                v-model="formData.connectionConfig.ssl.ca"
                type="textarea"
                :rows="3"
                placeholder="请输入CA证书内容"
              />
            </el-form-item>
            <el-form-item label="客户端证书" prop="connectionConfig.ssl.cert">
              <el-input
                v-model="formData.connectionConfig.ssl.cert"
                type="textarea"
                :rows="3"
                placeholder="请输入客户端证书内容"
              />
            </el-form-item>
            <el-form-item label="客户端密钥" prop="connectionConfig.ssl.key">
              <el-input
                v-model="formData.connectionConfig.ssl.key"
                type="textarea"
                :rows="3"
                placeholder="请输入客户端密钥内容"
              />
            </el-form-item>
          </template>

          <!-- SASL/SCRAM 认证配置 -->
          <template v-else-if="formData.connectionConfig.authType === 'sasl_scram'">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名" prop="connectionConfig.saslScram.username">
                  <el-input v-model="formData.connectionConfig.saslScram.username" placeholder="请输入用户名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="密码" prop="connectionConfig.saslScram.password">
                  <el-input
                    v-model="formData.connectionConfig.saslScram.password"
                    type="password"
                    placeholder="请输入密码"
                    show-password
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="算法" prop="connectionConfig.saslScram.algorithm">
              <el-select
                v-model="formData.connectionConfig.saslScram.algorithm"
                placeholder="请选择SCRAM算法"
                style="width: 100%"
              >
                <el-option label="SCRAM-SHA-256" value="sha256" />
                <el-option label="SCRAM-SHA-512" value="sha512" />
              </el-select>
            </el-form-item>
          </template>

          <el-form-item label="其他配置" prop="connectionConfig.extraConfigs">
            <el-button
              type="primary"
              size="small"
              @click="addExtraConfig"
              style="margin-bottom: 10px"
            >
              添加配置项
            </el-button>
            <el-table
              :data="formData.connectionConfig.extraConfigs"
              border
              style="width: 100%"
              empty-text="暂无额外配置"
            >
              <el-table-column prop="key" label="配置项" width="300">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.key"
                    placeholder="例如: session.timeout.ms"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="value" label="配置值">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.value"
                    placeholder="例如: 30000"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeExtraConfig($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-tab-pane>

        <!-- 消费配置 -->
        <el-tab-pane label="消费配置" name="consumer">
          <el-form-item label="消费组ID" prop="consumerConfig.groupId">
            <el-input 
              v-model="formData.consumerConfig.groupId" 
              placeholder="请输入消费组ID"
            />
          </el-form-item>

          <el-form-item label="消费主题" prop="consumerConfig.topics">
            <el-button
              type="primary"
              size="small"
              @click="addTopic"
              style="margin-bottom: 10px"
            >
              添加主题
            </el-button>
            <el-table
              :data="formData.consumerConfig.topics"
              border
              style="width: 100%"
              empty-text="暂无消费主题配置"
            >
              <el-table-column prop="topic" label="主题名称" width="300">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.topic"
                    placeholder="例如: user_activity"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="partition" label="分区" width="120">
                <template #default="{ row, $index }">
                  <el-select 
                    v-model="row.partition" 
                    placeholder="选择分区"
                    style="width: 100%"
                  >
                    <el-option label="全部" :value="-1" />
                    <el-option 
                      v-for="i in 10" 
                      :key="i" 
                      :label="`分区 ${i-1}`" 
                      :value="i-1" 
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="offsetReset" label="重置偏移" width="150">
                <template #default="{ row, $index }">
                  <el-select 
                    v-model="row.offsetReset" 
                    placeholder="选择偏移"
                    style="width: 100%"
                  >
                    <el-option label="最早" value="earliest" />
                    <el-option label="最新" value="latest" />
                    <el-option label="指定偏移" value="specific" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeTopic($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item label="消费线程数" prop="consumerConfig.threadCount">
            <el-input-number
              v-model="formData.consumerConfig.threadCount"
              :min="1"
              :max="32"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="批量消费" prop="consumerConfig.batchConsume">
            <el-switch v-model="formData.consumerConfig.batchConsume" />
          </el-form-item>

          <template v-if="formData.consumerConfig.batchConsume">
            <el-form-item label="批量大小" prop="consumerConfig.batchSize">
              <el-input-number
                v-model="formData.consumerConfig.batchSize"
                :min="1"
                :max="1000"
                controls-position="right"
                style="width: 100%"
              />
              <span class="el-form-item__tip">每次消费的最大消息数量</span>
            </el-form-item>
            <el-form-item label="超时时间(ms)" prop="consumerConfig.batchTimeout">
              <el-input-number
                v-model="formData.consumerConfig.batchTimeout"
                :min="100"
                :max="60000"
                controls-position="right"
                style="width: 100%"
              />
              <span class="el-form-item__tip">等待批量消息的超时时间</span>
            </el-form-item>
          </template>

          <el-form-item label="自动提交" prop="consumerConfig.autoCommit">
            <el-switch v-model="formData.consumerConfig.autoCommit" />
          </el-form-item>

          <template v-if="!formData.consumerConfig.autoCommit">
            <el-form-item label="提交间隔(ms)" prop="consumerConfig.commitInterval">
              <el-input-number
                v-model="formData.consumerConfig.commitInterval"
                :min="100"
                :max="60000"
                controls-position="right"
                style="width: 100%"
              />
              <span class="el-form-item__tip">手动提交时的提交间隔</span>
            </el-form-item>
          </template>
        </el-tab-pane>

        <!-- 数据处理 -->
        <el-tab-pane label="数据处理" name="processing">
          <el-form-item label="消息格式" prop="processingConfig.messageFormat">
            <el-select
              v-model="formData.processingConfig.messageFormat"
              placeholder="请选择消息格式"
              style="width: 100%"
            >
              <el-option label="JSON" value="json" />
              <el-option label="Avro" value="avro" />
              <el-option label="Protobuf" value="protobuf" />
              <el-option label="String" value="string" />
              <el-option label="Binary" value="binary" />
            </el-select>
          </el-form-item>

          <template v-if="formData.processingConfig.messageFormat === 'avro'">
            <el-form-item label="Schema注册URL" prop="processingConfig.schemaRegistryUrl">
              <el-input
                v-model="formData.processingConfig.schemaRegistryUrl"
                placeholder="请输入Schema注册中心URL"
              />
            </el-form-item>
            <el-form-item label="Schema ID" prop="processingConfig.schemaId">
              <el-input
                v-model="formData.processingConfig.schemaId"
                placeholder="请输入Schema ID"
              />
            </el-form-item>
          </template>

          <template v-else-if="formData.processingConfig.messageFormat === 'protobuf'">
            <el-form-item label="Proto文件" prop="processingConfig.protoFile">
              <el-input
                v-model="formData.processingConfig.protoFile"
                type="textarea"
                :rows="3"
                placeholder="请输入Proto文件内容"
              />
            </el-form-item>
            <el-form-item label="消息类型" prop="processingConfig.messageType">
              <el-input
                v-model="formData.processingConfig.messageType"
                placeholder="请输入消息类型全名"
              />
            </el-form-item>
          </template>

          <el-form-item label="时间戳字段" prop="processingConfig.timestampField">
            <el-input
              v-model="formData.processingConfig.timestampField"
              placeholder="例如: timestamp (留空表示不使用)"
            />
          </el-form-item>

          <el-form-item label="消息过滤" prop="processingConfig.filterEnabled">
            <el-switch v-model="formData.processingConfig.filterEnabled" />
          </el-form-item>

          <template v-if="formData.processingConfig.filterEnabled">
            <el-form-item label="过滤条件" prop="processingConfig.filterCondition">
              <el-input
                v-model="formData.processingConfig.filterCondition"
                type="textarea"
                :rows="3"
                placeholder="输入JavaScript条件表达式，例如: payload.temperature > 30"
              />
              <span class="el-form-item__tip">满足条件的消息才会被处理</span>
            </el-form-item>
          </template>

          <el-form-item label="消息转换" prop="processingConfig.transformEnabled">
            <el-switch v-model="formData.processingConfig.transformEnabled" />
          </el-form-item>

          <template v-if="formData.processingConfig.transformEnabled">
            <el-form-item label="转换脚本" prop="processingConfig.transformScript">
              <el-input
                v-model="formData.processingConfig.transformScript"
                type="textarea"
                :rows="5"
                placeholder="输入JavaScript转换脚本，例如: return { ...payload, processed: true }"
              />
              <span class="el-form-item__tip">可对消息内容进行转换处理</span>
            </el-form-item>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
        <el-button type="success" @click="testConnection">测试连接</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'EditKafkaDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'submit', 'test-connection'],
  setup(props, { emit }) {
    const visible = computed({
      get: () => props.modelValue,
      set: (val) => emit('update:modelValue', val)
    })

    const title = computed(() => 
      props.editData ? '编辑Kafka数据源' : '新增Kafka数据源'
    )

    const activeTab = ref('basic')
    const formRef = ref(null)

    // 默认表单数据
    const defaultFormData = {
      id: '',
      name: '',
      description: '',
      status: 1,
      connectionConfig: {
        clusterMode: false,
        single: {
          host: 'localhost',
          port: 9092
        },
        cluster: {
          brokers: [
            { host: 'localhost', port: 9092 }
          ]
        },
        clientId: '',
        authType: 'none',
        saslPlain: {
          username: '',
          password: ''
        },
        ssl: {
          ca: '',
          cert: '',
          key: ''
        },
        saslScram: {
          username: '',
          password: '',
          algorithm: 'sha256'
        },
        extraConfigs: []
      },
      consumerConfig: {
        groupId: `group_${Math.random().toString(36).substr(2, 8)}`,
        topics: [
          { topic: '', partition: -1, offsetReset: 'latest' }
        ],
        threadCount: 1,
        batchConsume: false,
        batchSize: 10,
        batchTimeout: 1000,
        autoCommit: true,
        commitInterval: 5000
      },
      processingConfig: {
        messageFormat: 'json',
        schemaRegistryUrl: '',
        schemaId: '',
        protoFile: '',
        messageType: '',
        timestampField: '',
        filterEnabled: false,
        filterCondition: '',
        transformEnabled: false,
        transformScript: ''
      }
    }

    const formData = ref(JSON.parse(JSON.stringify(defaultFormData)))

    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: '请输入数据源名称', trigger: 'blur' },
        { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
      ],
      'connectionConfig.single.host': [
        { 
          validator: (rule, value, callback) => {
            if (!formData.value.connectionConfig.clusterMode && !value) {
              return callback(new Error('请输入服务器地址'))
            }
            callback()
          },
          trigger: 'blur'
        }
      ],
      'connectionConfig.cluster.brokers': [
        { 
          validator: (rule, value, callback) => {
            if (formData.value.connectionConfig.clusterMode && (!value || value.length === 0)) {
              return callback(new Error('至少需要配置一个Broker'))
            }
            const hasEmpty = value.some(broker => !broker.host)
            if (hasEmpty) {
              callback(new Error('Broker地址不能为空'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        }
      ],
      'connectionConfig.saslPlain.username': [
        { 
          validator: (rule, value, callback) => {
            if (formData.value.connectionConfig.authType === 'sasl_plain' && !value) {
              return callback(new Error('请输入用户名'))
            }
            callback()
          },
          trigger: 'blur'
        }
      ],
      'connectionConfig.ssl.ca': [
        { 
          validator: (rule, value, callback) => {
            if (formData.value.connectionConfig.authType === 'ssl' && !value) {
              return callback(new Error('请输入CA证书'))
            }
            callback()
          },
          trigger: 'blur'
        }
      ],
      'consumerConfig.groupId': [
        { required: true, message: '请输入消费组ID', trigger: 'blur' }
      ],
      'consumerConfig.topics': [
        { 
          validator: (rule, value, callback) => {
            if (!value || value.length === 0) {
              return callback(new Error('至少需要配置一个消费主题'))
            }
            const hasEmpty = value.some(topic => !topic.topic)
            if (hasEmpty) {
              callback(new Error('主题名称不能为空'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        }
      ],
      'processingConfig.schemaRegistryUrl': [
        { 
          validator: (rule, value, callback) => {
            if (formData.value.processingConfig.messageFormat === 'avro' && !value) {
              return callback(new Error('请输入Schema注册中心URL'))
            }
            callback()
          },
          trigger: 'blur'
        }
      ]
    }

    // 添加Broker
    const addBroker = () => {
      formData.value.connectionConfig.cluster.brokers.push({
        host: '',
        port: 9092
      })
    }

    // 删除Broker
    const removeBroker = (index) => {
      formData.value.connectionConfig.cluster.brokers.splice(index, 1)
    }

    // 添加额外配置
    const addExtraConfig = () => {
      formData.value.connectionConfig.extraConfigs.push({
        key: '',
        value: ''
      })
    }

    // 删除额外配置
    const removeExtraConfig = (index) => {
      formData.value.connectionConfig.extraConfigs.splice(index, 1)
    }

    // 添加主题
    const addTopic = () => {
      formData.value.consumerConfig.topics.push({
        topic: '',
        partition: -1,
        offsetReset: 'latest'
      })
    }

    // 删除主题
    const removeTopic = (index) => {
      formData.value.consumerConfig.topics.splice(index, 1)
    }

    // 处理集群模式变化
    const handleClusterModeChange = (isCluster) => {
      // 重置相关配置
      if (isCluster) {
        formData.value.connectionConfig.single = JSON.parse(JSON.stringify(defaultFormData.connectionConfig.single))
      } else {
        formData.value.connectionConfig.cluster = JSON.parse(JSON.stringify(defaultFormData.connectionConfig.cluster))
      }
    }

    // 处理认证类型变化
    const handleAuthTypeChange = (type) => {
      // 重置其他认证类型的配置
      if (type !== 'sasl_plain') {
        formData.value.connectionConfig.saslPlain = JSON.parse(JSON.stringify(defaultFormData.connectionConfig.saslPlain))
      }
      if (type !== 'ssl') {
        formData.value.connectionConfig.ssl = JSON.parse(JSON.stringify(defaultFormData.connectionConfig.ssl))
      }
      if (type !== 'sasl_scram') {
        formData.value.connectionConfig.saslScram = JSON.parse(JSON.stringify(defaultFormData.connectionConfig.saslScram))
      }
    }

    // 测试连接
    const testConnection = async () => {
      try {
        await formRef.value.validateField([
          'connectionConfig.single.host',
          'connectionConfig.cluster.brokers',
          'connectionConfig.authType',
          'connectionConfig.saslPlain.username',
          'connectionConfig.ssl.ca'
        ])
        
        const config = {
          clusterMode: formData.value.connectionConfig.clusterMode,
          brokers: formData.value.connectionConfig.clusterMode 
            ? formData.value.connectionConfig.cluster.brokers
            : [{ 
                host: formData.value.connectionConfig.single.host, 
                port: formData.value.connectionConfig.single.port 
              }],
          authType: formData.value.connectionConfig.authType,
          authConfig: {}
        }

        if (formData.value.connectionConfig.authType === 'sasl_plain') {
          config.authConfig = {
            username: formData.value.connectionConfig.saslPlain.username,
            password: formData.value.connectionConfig.saslPlain.password
          }
        } else if (formData.value.connectionConfig.authType === 'ssl') {
          config.authConfig = {
            ca: formData.value.connectionConfig.ssl.ca,
            cert: formData.value.connectionConfig.ssl.cert,
            key: formData.value.connectionConfig.ssl.key
          }
        } else if (formData.value.connectionConfig.authType === 'sasl_scram') {
          config.authConfig = {
            username: formData.value.connectionConfig.saslScram.username,
            password: formData.value.connectionConfig.saslScram.password,
            algorithm: formData.value.connectionConfig.saslScram.algorithm
          }
        }

        emit('test-connection', config)
      } catch (error) {
        console.error('连接测试验证失败:', error)
        ElMessage.error('请检查连接配置是否正确')
      }
    }

    // 对话框关闭
    const handleClosed = () => {
      formRef.value?.resetFields()
      formData.value = JSON.parse(JSON.stringify(defaultFormData))
    }

    // 提交表单
    const submitForm = async () => {
      try {
        await formRef.value.validate()
        
        // 处理集群配置
        const finalData = JSON.parse(JSON.stringify(formData.value))
        if (finalData.connectionConfig.clusterMode) {
          delete finalData.connectionConfig.single
        } else {
          delete finalData.connectionConfig.cluster
        }
        
        // 清理未使用的认证配置
        if (finalData.connectionConfig.authType !== 'sasl_plain') {
          delete finalData.connectionConfig.saslPlain
        }
        if (finalData.connectionConfig.authType !== 'ssl') {
          delete finalData.connectionConfig.ssl
        }
        if (finalData.connectionConfig.authType !== 'sasl_scram') {
          delete finalData.connectionConfig.saslScram
        }
        
        emit('submit', finalData)
        visible.value = false
      } catch (error) {
        console.error('表单验证失败:', error)
        ElMessage.error('请检查表单填写是否正确')
      }
    }

    // 监听编辑数据变化
    watch(() => props.editData, (newVal) => {
      if (newVal) {
        formData.value = JSON.parse(JSON.stringify({
          ...defaultFormData,
          ...newVal,
          connectionConfig: {
            ...defaultFormData.connectionConfig,
            ...(newVal.connectionConfig || {}),
            single: {
              ...defaultFormData.connectionConfig.single,
              ...(newVal.connectionConfig?.single || {})
            },
            cluster: {
              ...defaultFormData.connectionConfig.cluster,
              ...(newVal.connectionConfig?.cluster || {}),
              brokers: newVal.connectionConfig?.cluster?.brokers || [...defaultFormData.connectionConfig.cluster.brokers]
            },
            saslPlain: {
              ...defaultFormData.connectionConfig.saslPlain,
              ...(newVal.connectionConfig?.saslPlain || {})
            },
            ssl: {
              ...defaultFormData.connectionConfig.ssl,
              ...(newVal.connectionConfig?.ssl || {})
            },
            saslScram: {
              ...defaultFormData.connectionConfig.saslScram,
              ...(newVal.connectionConfig?.saslScram || {})
            },
            extraConfigs: newVal.connectionConfig?.extraConfigs || []
          },
          consumerConfig: {
            ...defaultFormData.consumerConfig,
            ...(newVal.consumerConfig || {}),
            topics: newVal.consumerConfig?.topics || [...defaultFormData.consumerConfig.topics]
          },
          processingConfig: {
            ...defaultFormData.processingConfig,
            ...(newVal.processingConfig || {})
          }
        }))
      }
    }, { immediate: true })

    return {
      visible,
      title,
      activeTab,
      formRef,
      formData,
      formRules,
      addBroker,
      removeBroker,
      addExtraConfig,
      removeExtraConfig,
      addTopic,
      removeTopic,
      handleClusterModeChange,
      handleAuthTypeChange,
      testConnection,
      handleClosed,
      submitForm
    }
  }
}
</script>

<style scoped>
.el-form-item__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  display: inline-block;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>